<?php

require_once WACT_ROOT . '/db/db.inc.php';
require_once WACT_ROOT . '/util/dataspace.inc.php';

class PaymentFilter {
    function doFilter(&$vars){
    	$vars['date']=substr($vars['date'],0,10);
    	$vars['payamount']=number_format($vars['payamount'],2);
    	if($vars['paystatus']==1) $vars['paystatus']='Completed';
    	else  $vars['paystatus']='Failed';
    }
}

class Payment {

  function &getRecord($payment_id) {
       return DBC::FindRecord("
       SELECT P.* FROM sport_payments P
       WHERE P.payment_id = ". DBC::makeLiteral($payment_id));
  }

  function &getID($txn_id) {
       $id = 0;
       $rs =& DBC::FindRecord("
       SELECT P.payment_id FROM sport_payments P
       WHERE P.txn_id =". DBC::makeLiteral($txn_id));
       if ($rs) $id = $rs->get('payment_id');
       return $id;
  }

  function existPayment($txn_id) {
       $rs =& DBC::FindRecord("
       SELECT P.* FROM sport_payments P
       WHERE P.txn_id =". DBC::makeLiteral($txn_id));
       return !is_null($rs);
  }

  function insertPayment(&$data) {
        $txn_id = $data->get('txn_id');
  		$exist = Payment::existPayment($txn_id);
  		if ( $exist ) {
  			$id = Payment::getID( $txn_id );
  			return $id;
  		}
        $Record =& DBC::NewRecord($data);
        $id = $Record->insertId('sport_payments',
            array('txn_id','date', 'subscription_id',
            'amount', 'status'),'payment_id');
        return $id;
  }

 // get payments for subscription
 function &getListForSubscription($subscription_id, &$Pager) {
 	if($Pager==null)
 		return DBC::NewRecordSet(
        		'SELECT P.*, S.*, U.*,P.status as paystatus,P.amount as payamount
        		FROM sport_payments P
        		inner join sport_subscriptions S on S.id = P.subscription_id
        		inner join sport_users U on S.user_id = U.user_id
        		where S.id = '. DBC::makeLiteral($subscription_id). '
        		order BY P.`date` desc',new PaymentFilter());
   else
        return DBC::NewPagedRecordSet(
        		'SELECT P.*, S.*, U.*
        		FROM sport_payments P
        		inner join sport_subscriptions S on S.id = P.subscription_id
        		inner join sport_users U on S.user_id = U.user_id
        		where S.id = '. DBC::makeLiteral($subscription_id). '
        		order BY P.`date` desc', $Pager);
    }

    // get payments for user
 function &getListForUser($user_id, &$Pager) {
        return DBC::NewPagedRecordSet(
        		'SELECT P.*, S.*, U.*
        		FROM sport_payments P
        		inner join sport_subscriptions S on S.id = P.subscription_id
        		inner join sport_users U on S.user_id = U.user_id
        		where S.user_id = '. DBC::makeLiteral($user_id). '
        		order BY P.`date` desc', $Pager);
    }

    // 1 - Active
// 0 - Finished
function &getHumanStatus($status) {
	if ($status==1) return 'Completed';
	elseif ($status==0) return 'Failed';
    else  return 'N/A';
}


}

?>